﻿CREATE PROCEDURE [dbo].[Inventories_UpdateFromTempInventories]
AS
	UPDATE Inventories
	SET ArticleId = temp.ArticleId, 
		StoreId = temp.StoreId,
		Date = temp.Date,
		Description = temp.Description,		  
		Quantity = temp.Quantity,
		Cost = temp.Cost * ISNULL(repArtShare.SalesShare, 1),
		Retail = temp.Retail,
		GP = temp.GP
	FROM Inventories inv 
	Inner join TempInventories temp on inv.Date = temp.Date and inv.ArticleId = temp.ArticleId and inv.StoreId = temp.StoreId
	LEFT JOIN
	(
		select  distinct a.Id, a.Code, a.UOM, SUM(isnull(s.Sales, 0) / rep.CodeSales) SalesShare
		from Articles a
		Left join 
		(
			select Code, SUM(convert(decimal(18,4),Sales)) CodeSales
			from Articles ar 
			left join ArticleSales s on s.ArticleId = ar.Id
			where ar.Code in (select Code from Articles group by Code having COUNT(*) > 1)
			group by Code		
		) as rep on rep.Code = a.Code
		left join ArticleSales s on a.Id = s.ArticleId
		group by a.Id, a.Code, a.UOM
	) repArtShare on repArtShare.Id = inv.ArticleId
	Where     
		ISNULL(temp.Cost,0) > 0